package com.joshua.open.mybatis.dao;

import com.joshua.open.mybatis.entity.User;
import com.joshua.open.mybatis.util.MybSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * projectName mybatis-note
 * package com.joshua.open.mybatis.dao
 * classname  UserDao
 * <p>
 * description
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/12/31 17:44
 */
public class UserDao {
    private SqlSession session = MybSessionUtil.getSession();

    public int insert(User user) {
        // 第一个参数是mapper.xml里的namespace + MappedStatement对应的id
        int result = session.insert("openM1.insertUser", user);
        // 不要忘记提交
        session.commit();
        return result;
    }

    public List<User> findUserByName(String value) {
        List<User> users = session.selectList("openM1.findUserByName", value);
        return users;
    }

    public void deleteUser(String id) {
        session.delete("openM1.deleteUser", id);
        session.commit();
    }

    public void updateUser(User user) {
        session.update("openM1.updateUser", user);
        session.commit();
    }


    public static void main(String[] args) {
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername("t1");
        user.setPassword("pwd");
        if (userDao.insert(user) == 1) {
            System.out.println("insert success...");
        } else {
            System.out.println("insert fail...");
        }
        String value = "t";
        List<User> list = userDao.findUserByName(value);
        System.out.println(list.toString());
        if (null != list && list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i == 0) {
                    userDao.deleteUser(list.get(i).getId());
                }
                if (i == 1) {
                    User oUser = list.get(i);
                    oUser.setUsername(String.format("new-add%s",System.currentTimeMillis()));
                    userDao.updateUser(oUser);
                }
            }
        }
    }
}
